<template>
	<view class="col-auto col">
		<view class="gt-admin-list col-auto">
			<!-- 顶部 -->
			<view class="gt-admin-list-content col col-auto ">
				<view class="row">
					<view class="row-auto">
						<!-- 搜索 -->
						<gt-form v-if="value.search" :template="value.search" v-model="searchFormData"
							:selectList="selectList" :defaultClass="value.class || 'gt-form-border gt-form-sm row'"
							:btnClass="value.btnClass || 'btn btn-sm'"
							:defaultChildClass="value.defaultChildClass || 'gt-form-block-sm mr-10'"
							:defaultChildStyle="value.defaultChildStyle || ''" @submit="getListData"
							@clickBack="clickBack"></gt-form>
					</view>
					<view class="ml-10 row-nowrap" >
						<gt-select-tab v-if="value.tab" :class="value.tab.class || 'gt-form-border gt-form-sm row'" v-model="searchFormData[value.tab.field]"
							:list="selectList[value.tab.field] || []" @clickBack="clickBack"></gt-select-tab>
						<uni-icons type="gear" class="ml-10 pointer" size="22px"
							@click="$refs.selectShowField.open()"></uni-icons>
					</view>
				</view>
				<!-- 列表 -->
				<view class="col-auto"
					style="overflow-y: auto;height: 300px;border:1px solid #eee;border-radius: 10px;">
					<!-- style="overflow-y: auto;height: 300px;box-shadow:inset 0px 0px 5px #e5e5e5;border-radius: 10px;"> -->
					<!-- {{ selectList }} -->
					<gt-admin-table class="col-auto" :table="temp.table" :list="list" :selectList="selectList"
						@clickBack="clickBack" @clickCell="clickCell" @selectCheckBox="selectCheckBox"></gt-admin-table>
				</view>

			</view>
			<view class="gt-admin-list-bottom row">
				<view class="row-auto row" v-if="value.table.batchBtn">
					<view class="btn btn-sm mr-15" v-for="(item,index) in value.table.batchBtn" :key="index"
						:class="batchBtnClass(item)" @click="batchBtnClick(item)">{{ item.label }}</view>
				</view>
				<gt-admin-page-info :pageInfo="pageInfo" @pageInfoChange="pageInfoChange"></gt-admin-page-info>
			</view>
		</view>
		<!-- 弹层 -->
		<uni-popup ref="popup" :type="formTemplate.type || 'right'">
			<view style="background-color: #fff;overflow-y: auto;position: relative;"
				:style="TopNavExist ? 'height: calc( 100vh - 50px );' : 'height:100vh'">
				<view class="gt-popup-close" @click="closePopup">
					<uni-icons type="closeempty" class="gt-popup-close-icon"
						style="line-height: 24px;font-size: 22px;color:#999999;"></uni-icons>
				</view>
				<view class="popup-title">{{ formTemplate.title }}</view>
				<view class="pd-30" style="position:  relative;">
					<gt-form :template="formTemplate.form" :formData="formData" :selectList="selectList"
						@submit="formSubmit">
					</gt-form>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="view" :type="formTemplate.type || 'right'">
			<view style="background-color: #fff;overflow-y: auto;position: relative;"
				:style="TopNavExist ? 'height: calc( 100vh - 50px );' : 'height:100vh'">
				<view class="gt-popup-close" @click="closePopup">
					<uni-icons type="closeempty" class="gt-popup-close-icon"
						style="line-height: 24px;font-size: 22px;color:#999999;"></uni-icons>
				</view>
				<view class="popup-title">{{formTemplate.title}}{{ TopNavExist }}</view>
				<view class="pd-30" style="position:  relative;">
				</view>
			</view>
		</uni-popup>
		<uni-popup type="center" ref="selectShowField">
			<view class="pd-30 b-r-10 bg-fff" style="width: 380px;">
				<view class="t-lg t-center mb-30">选择显示</view>
				<view class="row">
					<view class="" v-for="(item,index) in value.table.columns" :key="index" class="xs-1-2 row mb-10">
						<uni-icons v-if="selectShowField.indexOf(index) == -1" type="circle" size="24px" color="#ccc"
							class="pointer" @click="selectShowFieldAdd(index)"></uni-icons>
						<uni-icons v-else type="circle-filled" size="24px" color="#409EFF" class="pointer"
							@click="selectShowFieldRemove(index)"></uni-icons>
						<view class="ml-10 t-md">{{ item.label }}</view>
					</view>
				</view>

			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		name: "gt-admin-list",
		props: {
			value: {
				type: Object,
				default: () => {
					return {};
				}
			},
		},
		data() {
			return {
				list: [],
				pageInfo: {
					page: 0,
					limit: 10,
					totalPage: 1
				},
				selectList: {},
				searchFormData: {},
				selectCheckBoxList: [],

				formTemplate: {},
				formData: {},
				TopNavExist: false,
				temp: {},
				selectShowField: [],
			}
		},
		async created() {
			this.selectShowFieldChange();

			let dom = document.getElementsByTagName('uni-top-window');
			this.TopNavExist = dom.length > 0 ? true : false;
			//搜索表单
			let searchFormData = {};
			if (this.value.tab && this.value.tab.field) searchFormData[this.value.tab.field] = '';
			if (this.value['searchFormData']) {
				searchFormData = this.value['searchFormData']
			}
			for (let i in this.value.search.items) {
				let item = this.value.search.items[i];
				if (item.field) searchFormData[item.field] = item.value || '';
			}
			this.searchFormData = searchFormData;
			//
			let selectList = {};
			for (let i in this.value.selectList) {
				selectList[i] = this.value.selectList[i];
			}
			this.selectList = selectList;
			//获取数据列表
			await this.getListData();
			//获取选择列表
			await this.getSelectListData();
		},
		methods: {
			selectShowFieldAdd(index) {
				let i = this.selectShowField.indexOf(index);
				if (i == -1) {
					this.selectShowField.push(index);
				}
				this.selectShowFieldChange(true);
			},
			selectShowFieldRemove(index) {

				let i = this.selectShowField.indexOf(index);
				if (i != -1) {
					this.selectShowField.splice(i, 1);
				}
				this.selectShowFieldChange(true);
			},
			selectShowFieldChange(status) {
				if (status) {
					let router = this.$fun.getRouter();
					this.$fun.setCache('field_' + router, this.selectShowField);
				} else {
					let router = this.$fun.getRouter();
					let selectShowField = this.$fun.getCache('field_' + router);
					if(selectShowField) this.selectShowField = selectShowField;
					
				}
				let temp = JSON.parse(JSON.stringify(this.value));
				for(let i in this.value.table.columns){
					let col = this.value.table.columns[i];
					temp.table.columns[i] = col;
				}
				if (this.selectShowField.length == 0) {
					this.temp = temp;
					return false;
				}
				let columns = [];
				for (let i in this.value.table.columns) {
					if (this.selectShowField.indexOf(parseInt(i)) != -1) {
						columns.push(this.value.table.columns[i]);
					}
				}
				temp.table.columns = columns;
				this.temp = temp;
			},
			formSubmit(e) {
				if (e.response && e.response.msg) {
					this.getListData();
					this.$refs.popup.close();
				}
			},
			clickBackPopup(item, data) {
				if (item.popup.form) {
					if (typeof item.popup.form == 'string' && this.value.form[item.popup.form]) {
						item.popup.form = this.value.form[item.popup.form];
					}
					if (item.url) {
						item.popup.form.url = item.url;
					}
					if (!item.popup.form.url) {
						// console.log('请求地址为空！');
						return;
					}
					if (data) {
						let formData = {};
						for (let i in item.popup.form.items) {
							let row = item.popup.form.items[i]
							if (row.field && data[row.field] && row.type == 'json' && row.items) {
								formData[row.field] = JSON.parse(data[row.field]);
								// console.log(formData[row.field]);
							}
							if (row.field && data[row.field] && row.type == 'json_array' && row.items) {
								formData[row.field] = JSON.parse(data[row.field]);
								// console.log(formData[row.field]);
							} else if (row.field && data.hasOwnProperty(row.field)) {
								formData[row.field] = data[row.field];
							} else if (row.field) {
								formData[row.field] = '';
							}
						}
						let url = item.url;
						if (item.urlParams) {
							for (let i in item.urlParams) {
								let field = item.urlParams[i];
								if (!data[field]) {
									console.log('请求参数值不存在');
									return;
								} else {
									url += url.indexOf('?') == -1 ? '?' : '&';
									url += field + '=' + data[field];
								}
							}
						}
						item.popup.form.requestType = item.requestType || '';
						item.popup.form.url = url;
						this.formTemplate = item.popup;
						console.log(formData)
						this.formData = formData;
					} else {
						let formData = {};
						if (item.defaultFieldBySearch) {
							for (let index in item.defaultFieldBySearch) {
								let defaultField = item.defaultFieldBySearch[index];
								// console.log(this.value.searchFormData[defaultField]);
								if (this.value.searchFormData[defaultField] !== undefined) {
									formData[defaultField] = this.value.searchFormData[defaultField];
								}
							}
						}
						// console.log(formData);

						for (let i in item.popup.form.items) {
							let row = item.popup.form.items[i]
							if (row.field && row.type == 'json') {
								let tempJson = {};
								for (let i in row.items) {
									if (row.items[i].field) {
										tempJson[row.items[i].field] = '';
									}
								}
								formData[row.field] = tempJson;
							} else if (row.field && row.type == 'json_array') {
								let tempJson = {};
								let tempJsonArr = [];
								for (let i in row.items) {
									if (row.items[i].field) {
										tempJson[row.items[i].field] = '';
									}
								}
								tempJsonArr.push(tempJson);
								// console.log(tempJsonArr);
								formData[row.field] = tempJsonArr;
							} else if (row.field) {
								formData[row.field] = formData[row.field] === undefined ? '' : formData[row.field];
							}
						}
						this.formTemplate = item.popup;
						this.formData = formData;

					}
					// console.log(this.$refs.popup);
					this.$refs.popup.open();
				}
			},
			clickCell(column, row, rowIndex) {
				this.$emit('clickCell', column, row, rowIndex)
			},
			clickBack(item, data) {
				console.log('clickBack', item, data);
				if (!item) {
					this.getListData();
				} else if (item.type && item.type == 'search') { //搜索
					this.getListData({
						page: 1
					});
				} else if (item.type && item.type == 'batch') { //批量选择
					this.batch(item);
				} else if (item.click) { //回调点击事件
					let pages = getCurrentPages();
					let page = pages[pages.length - 1];
					item.click(item, data, page);
				} else if (item.popup) { //弹层
					this.clickBackPopup(item, data);
				} else if (item.type && item.type == 'urlPost') {
					this.urlPost(item, data);
				}
			},
			urlPost(item, data) {
				let _this = this;
				uni.showModal({
					content: '确认' + item.label,
					// showCancel: false,
					success(resp) {
						// console.log(resp)
						if (resp.confirm && item.url) {
							let getParams = {};
							let urlParams = '';
							for (let i in item.urlParams) {
								let field = item.urlParams[i];
								let value = data[field] || '';
								getParams[field] = data[field] || '';
								urlParams += urlParams ? '&' : '?';
								urlParams += field + '=' + value;
							}
							_this.$post({
								url: item.url + urlParams,
								data: getParams,
								type: item.requestType || '',
								afterFun(r) {
									if (!r.error) {
										_this.getListData();
									}
								}
							})
						}
					}
				});

			},
			selectCheckBox(e) {
				let _this = this;
				this.selectCheckBoxList = e;
				_this.$emit('selectCheckBox', {
					response: e
				})
			},
			batch(item) {
				let _this = this;
				if (!item.url) {
					console.log('无 url 参数');
					return;
				}
				if (!item.field) {
					console.log('无 field 参数');
					return;
				}
				let params = '';
				for (let i in this.batchSelectIndexList) {
					let index = this.batchSelectIndexList[i];
					let row = this.value.list[index];
					if (row[item.field]) {
						params += params ? ',' : '';
						params += row[item.field];
					}
				}
				uni.showModal({
					title: '警告',
					content: this.confirmText,
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							_this.$post({
								url: item.url + '?' + item.field + '=' + params,
								afterFun(r) {
									if (r.msg) {
										_this.batchSelectIndexList = [];
										_this.getListData();
									}
									_this.$emit('batchCallBack', {
										response: r
									})
								}
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			closePopup() {
				this.$refs.popup.close();
			},
			//获取选择列表
			async getSelectListData() {
				let _this = this;
				if (this.value.selectListUrl) {
					let selectList = {};
					for (let i in this.value.selectListUrl) {
						await this.$get({
							url: this.value.selectListUrl[i],
							loading: true,
							afterFun(resp) {
								if (resp) {
									// let p = {
									// 	list :{
									// 		lang:[{key:'***':val:'***'},...],
									// 		cate_en:[{key:'***':val:'***'},...],
									// 		cate_cn:[{key:'***':val:'***'},...],
									// 	}
									// }
									if (resp.list) {
										for (let field in resp.list) {
											selectList[field] = resp.list[field];
										}
									} else {
										for (let field in resp) {
											selectList[field] = resp[field];
										}
									}
								}
								// console.log(i)
							},
						});
					}

					_this.selectList = {
						..._this.selectList,
						...selectList,
					};
					// this.selectList = Object.assign(this.selectList, selectList);
					// this.changeTemp();
				}
			},
			//获取数据列表
			async getListData(params) {
				let _this = this;
				if (!this.value.table.listUrl) {
					console.log('未配置数据地址');
					return false;
				}
				// console.log('getListData');
				let page = params && params.page || (this.pageInfo.page ? this.pageInfo.page :
					1);
				let limit = params && params.limit || (this.pageInfo.limit || 10);
				let searchFormData = this.searchFormData || {};
				await this.$get({
					url: _this.value.table.listUrl,
					loading: true,
					data: {
						page: page,
						limit: limit,
						...searchFormData
					},
					afterFun(resp) {
						// let template = _this.$tools.assginData(_this.value);
						if (resp.list) {
							_this.list = resp.list
						}
						if (resp.pageInfo) {
							_this.pageInfo = resp.pageInfo;
						}
					},
				});
				// this.changeTemp();
			},
			changeTemp() {
				this.$emit('input', {
					...this.value,
					list: this.list,
					pageInfo: this.pageInfo,
					selectList: this.selectList,
					searchFormData: this.searchFormData,
					formTemplate: this.formTemplate,
					formData: this.formData,
				})
			},
			pageInfoChange(e) {
				this.getListData(e);
			},
			batchBtnClass(item) {
				if (this.selectCheckBoxList.length == 0) return 'btn-disabled';
				if (item.field == undefined) {
					console.log('item.field not found');
					return false;
				}
				if (item.eq == undefined) {
					console.log('item.eq not found');
					return false;
				}
				let count = 0;
				for (let i in this.list) {
					if (this.selectCheckBoxList.indexOf(parseInt(i)) != -1) {
						// console.log(this.list[i][item.field],item.eq)
						if (this.list[i][item.field] != item.eq) {
							break
						} else {
							count += 1;
						}
					}
				}
				if (count != 0 && this.list.length == count) {
					return item.class ? item.class : '';
				}
				return 'btn-disabled';
			},
			batchBtnClick(item) {
				console.log(item);
				for (let i in item.urlParams) {
					let field = item.urlParams[i];
					let params = [];
					for (let x in this.selectCheckBoxList) {
						let index = this.selectCheckBoxList[x];
						params.push(this.list[index][field]);
					}
					item.url += item.url.indexOf('?') == -1 ? '?' : '&';
					item.url += field + '=' + params.join(',');
				}
				let _this = this;
				this.$post({
					url: item.url,
					data: {},
					_this: this,
					afterFun(r) {
						_this.getListData();
					}
				})
			}
		}
	}
</script>

<style lang="scss">



</style>